//
//  AppDelegate.swift
//  fir-mac
//
//  Created by isaced on 16/6/22.
//
//

import Cocoa
import KeychainAccess

let KeychainFirmacServiceName = "com.fir-mac.jybhy.token"
let KeychainFirmacAPITokenKey = "api-token"
let KeychainFirmacTokenType = "token-type"

enum TokenType: String {
    case fir = "Fir"
    case pgy = "Pgy"
}

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var prepareUploadUrl: URL?
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {

    }
    
    func applicationWillFinishLaunching(_ notification: Notification) {
        NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(handleEvent(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
    }
    
    @objc func handleEvent(_ event: NSAppleEventDescriptor!, withReplyEvent: NSAppleEventDescriptor!) {
        if let path = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue {
            if let url = URL(string: path) {
                if let components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
                    if components.host ?? "" == "upload" {
                        for item in components.queryItems ?? [] {
                            if let filePath = item.value {
                                let fileUrl = URL(fileURLWithPath: filePath)
                                if self.prepareUploadUrl == nil {
                                    prepareUploadUrl = fileUrl
                                }
                                NotificationCenter.default.post(name: NSNotification.Name.FIRSchemeUploadAction, object: fileUrl)
                            }
                        }
                    }
                }
            }
        }
    }
    
    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
    
    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }
    
    @IBAction func githubMenuAction(_ sender: NSMenuItem) {
        NSWorkspace.shared.open(URL(string: "https://gitee.com/liudefa/fir-mac.git")!)
    }
    
    
    
    
}

